﻿//
// *************************************************************************************
// WP-Framework
//
// Developed by 
// Lukas Kretschmar (lkretschmar.dev@bluewin.ch)
//
// Switzerland, Copyright (c) 2012 lkretschmar
// This content is released under the MIT License (http://opensource.org/licenses/MIT).
//     
// *************************************************************************************
//
//
			

using System;
using System.Linq.Expressions;
using Expression = System.Linq.Expressions.Expression;
using KretschIT.WP_Fx.Core.I18n;

namespace KretschIT.WP_Fx.Core.Extensions
{
    public static class ExpressionExtensions
    {
        private static void IsNotNull(Expression expression)
        {
            if (expression == null)
            {
                throw new ArgumentNullException("expression");
            }
        }
        
        public static T Execute<T>(this Expression<Func<T>> expression)
        {
            IsNotNull(expression);
            return expression.Compile().Invoke();
        }

        public static TExpression To<TExpression>(this LambdaExpression expression) where TExpression : Expression
        {
            IsNotNull(expression);
            return TryConvert<TExpression>(expression);
        }

        private static TExpression TryConvert<TExpression>(LambdaExpression expression) where TExpression : Expression
        {
            if (expression.Body is TExpression)
            {
                return expression.Body as TExpression;
            }
            throw new ArgumentException(string.Format(Messages.Exception_ArgumentIsNot, typeof(TExpression).FullName));
        }

        public static object GetValue(this MemberExpression expression)
        {
            IsNotNull(expression);
            return Expression.Lambda(expression).Compile().DynamicInvoke();
        }
    }
}
